import 'package:flutter/foundation.dart';
import '../models/subscription.dart';
import '../models/server_config.dart';
import '../services/storage_service.dart';
import '../services/subscription_service.dart';
import '../widgets/subscription_update_result_dialog.dart';
import 'vpn_provider.dart';

class SubscriptionProvider with ChangeNotifier {
  final StorageService _storageService = StorageService();
  final SubscriptionService _subscriptionService = SubscriptionService();
  final VpnProvider _vpnProvider;

  List<Subscription> _subscriptions = [];
  bool _isUpdating = false;

  List<Subscription> get subscriptions => _subscriptions;
  bool get isUpdating => _isUpdating;

  SubscriptionProvider(this._vpnProvider) {
    _loadSubscriptions();
  }

  Future<void> _loadSubscriptions() async {
    _subscriptions = await _storageService.loadSubscriptions();
    notifyListeners();
  }

  Future<void> addSubscription(Subscription subscription) async {
    _subscriptions.add(subscription);
    await _storageService.saveSubscriptions(_subscriptions);
    notifyListeners();
  }

  Future<void> updateSubscription(Subscription subscription) async {
    final index = _subscriptions.indexWhere((s) => s.id == subscription.id);
    if (index != -1) {
      _subscriptions[index] = subscription;
      await _storageService.saveSubscriptions(_subscriptions);
      notifyListeners();
    }
  }

  Future<void> deleteSubscription(String subscriptionId) async {
    // 先找到订阅，获取其分组名称
    final subscription = _subscriptions.firstWhere(
      (s) => s.id == subscriptionId,
      orElse: () => throw Exception('Subscription not found'),
    );
    
    // 删除订阅
    _subscriptions.removeWhere((s) => s.id == subscriptionId);
    await _storageService.saveSubscriptions(_subscriptions);
    
    // 删除该订阅分组下的所有服务器
    await _vpnProvider.deleteServersByGroup(subscription.name);
    
    notifyListeners();
  }

  Future<SubscriptionUpdateResult> updateServersFromSubscription(String subscriptionId) async {
    _isUpdating = true;
    notifyListeners();

    try {
      final subscription = _subscriptions.firstWhere((s) => s.id == subscriptionId);
      
      // 获取当前订阅下的所有服务器（使用 allServers 获取未过滤的完整列表）
      final currentServers = _vpnProvider.allServers
          .where((s) => s.group == subscription.name)
          .toList();
      
      print('📊 Update Check for "${subscription.name}":');
      print('   Current servers in group: ${currentServers.length}');
      
      // 从订阅URL获取新的服务器列表
      final newServers = await _subscriptionService.fetchServers(subscription.url);
      
      print('   New servers from URL: ${newServers.length}');
      
      // 比较服务器列表，找出新增、删除和未变化的服务器
      final addedServers = <ServerConfig>[];
      final removedServers = <ServerConfig>[];
      final unchangedServers = <ServerConfig>[];

      // 找出新增的服务器（在newServers中但不在currentServers中）
      for (var newServer in newServers) {
        final exists = currentServers.any((current) =>
            current.address == newServer.address &&
            current.port == newServer.port &&
            current.protocol == newServer.protocol &&
            current.userId == newServer.userId);
        
        if (!exists) {
          addedServers.add(newServer);
          print('   ➕ Added: ${newServer.name} (${newServer.address}:${newServer.port})');
        } else {
          unchangedServers.add(newServer);
        }
      }

      // 找出删除的服务器（在currentServers中但不在newServers中）
      for (var currentServer in currentServers) {
        final exists = newServers.any((newSrv) =>
            newSrv.address == currentServer.address &&
            newSrv.port == currentServer.port &&
            newSrv.protocol == currentServer.protocol &&
            newSrv.userId == currentServer.userId);
        
        if (!exists) {
          removedServers.add(currentServer);
          print('   ➖ Removed: ${currentServer.name} (${currentServer.address}:${currentServer.port})');
        }
      }

      print('   Summary: +${addedServers.length} / -${removedServers.length} / =${unchangedServers.length}');

      // 删除旧服务器
      for (var server in removedServers) {
        await _vpnProvider.deleteServer(server.id);
      }

      // 添加新服务器
      for (var server in addedServers) {
        await _vpnProvider.addServer(server.copyWith(group: subscription.name));
      }

      // 更新订阅信息
      final updatedSubscription = Subscription(
        id: subscription.id,
        name: subscription.name,
        url: subscription.url,
        lastUpdate: DateTime.now(),
        serverCount: newServers.length,
        autoUpdate: subscription.autoUpdate,
        updateInterval: subscription.updateInterval,
      );

      await updateSubscription(updatedSubscription);

      return SubscriptionUpdateResult(
        addedCount: addedServers.length,
        removedCount: removedServers.length,
        unchangedCount: unchangedServers.length,
        addedServers: addedServers,
        removedServers: removedServers,
        subscriptionName: subscription.name,
      );
    } finally {
      _isUpdating = false;
      notifyListeners();
    }
  }

  Future<List<SubscriptionUpdateResult>> updateAllSubscriptions() async {
    final results = <SubscriptionUpdateResult>[];
    for (var subscription in _subscriptions) {
      final result = await updateServersFromSubscription(subscription.id);
      results.add(result);
    }
    return results;
  }
}
